local gamelib = require "club.threecard.gamelib"
local slotlib = require "club.threecard.slotlib"
local components = slotlib.require "components"

local slot_system = slotlib.systems.slot_system
local class = gamelib.entitas.class
local Matcher = gamelib.entitas.Matcher
local GroupEvent = gamelib.entitas.GroupEvent

local M = class("jackpot_system", slot_system)

function M:ctor(context, ingame)
    M.super.ctor(self, context, ingame)
    self.jackpot_win = slotlib.require("widget.JackpotWin").new()
end

function M:initialize()
    self.jackpot_win:load()
end

function M:get_trigger()
    return {{Matcher({components.frames_component}), GroupEvent.ADDED}}
end

function M:filter(entity)
    return entity:has(components.frames_component)
end

function M:execute(entitas)
    if entitas:size() ~= 1 then
        gamelib.log.error("数据错误，结果组件不可能>1")
        return
    end

    entitas:foreach(function(e)
        local frames = e:get(components.frames_component).frames
        if #frames == 0 then
            return
        end

        local jackpot_frame = nil
        for _, frame in ipairs(frames) do
            if frame.type == slotlib.frame_type.jackpot_hit then
                jackpot_frame = frame
                break
            end
        end

        if jackpot_frame == nil then
            return
        end

        local fx_root = self.ingame.fx_root
        local value = jackpot_frame.credits
        local time = self.jackpot_win:play(value, fx_root)
        self:wait(time)
        self.jackpot_win:close()
    end)
end

function M:skip()
    self.super.skip(self)
    self.jackpot_win:close()
end

function M:tear_down()
    self.jackpot_win:hide()
end

return M